from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth import authenticate,login,logout
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.core.mail import settings
from itsdangerous import SignatureExpired
from django.views.generic import View
from .models import *
import json
from celery_tasks.tasks import send_active_email
from django.http import JsonResponse
# Create your views here.

# 视图函数在该项目中使用的是类视图.因为类视图可读性好相对于函数视图有更高的复用性，如果其他地方需要用到某个类视图的某个特定逻辑，直接继承该类视图即可

#主页
class Index(View):
    def get(self,request):
        name = request.session.get('username')
        if name:  # 如果当前用户存在
            user = Hmsx.objects.get(username=name)
            return render(request,'hmsx/index.html',{'user':user})
        return render(request, 'hmsx/index.html', {'user':''})
    def post(self,request):
        pass

# 登录
class Login(View):
    def get(self,request):
        return render(request,'hmsx/login.html')
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        user = authenticate(username=username, password=password)
        if user:
            request.session['username'] = username  # 把用户名存到session中
            request.session.set_expiry(0)  # 过期时间（秒），默认两周
            return JsonResponse({"result": ""})
        else:
            return JsonResponse({"result":"用户名或密码不正确"})

# 注册
class Register(View):
    def get(self,request):
        return render(request,'hmsx/register.html')
    def post(self,request):
        username = request.POST.get('user_name')
        email = request.POST.get('email')
        if username or email:
            if Hmsx.objects.filter(username=username) or Hmsx.objects.filter(email=email):
                return HttpResponse(json.dumps({"result": "该用户已被注册","result1": "该邮箱已被注册",'pd':'1'}))
            else:
                return HttpResponse(json.dumps({"result": "用户名可用","result1": "该邮箱可用"}))


class Reg(View):
    def post(self,request):
        username = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        email = request.POST.get('email')
        if username and pwd and email:
            Hmsx.objects.create_user(username=username, password=pwd, email=email)
            return redirect('hmsx:login')
        return redirect('hmsx:register')

# 退出
class Dele(View):
    def get(self,request):
        request.session.flush()  # 注销掉session里的数据
        return redirect('hmsx:index')

# 用户信息
class Info(View):
    def get(self,request):
        name = request.session.get('username')
        if name:  # 如果当前用户存在
            user = Hmsx.objects.get(username=name)
            return render(request, 'hmsx/user_center_info.html',{'user': user})
        return render(request,'hmsx/user_center_info.html',{'user':''})
    def post(self,request):
        iphon = request.POST.get('phone')
        name = request.session.get('username')
        if iphon:
            Hmsx.objects.filter(username=name).update(iphon=iphon)
            return redirect('hmsx:info')

# 邮件发送
class Regis(View):
    def post(self,request):
        name = request.session.get('username')
        user = Hmsx.objects.get(username=name)
        if user:
            username = user.name
            uname = user.username
            serializer = Serializer(settings.SECRET_KEY,3600)   # 用户的ID加密，生成激活的token
            info = {"confirm":user.id}   # 获取需要加密的信息用户的ID，存储成字典的形式
            token = serializer.dumps(info)  # 信息的加密
            send_active_email(user.email,username,uname,token)
            return JsonResponse({"result": "邮箱发送成功请前往激活"})
        return redirect('register')

# 激活操作
class Active(View):
    def get(self,request,token):
        serializer=Serializer(settings.SECRET_KEY,3600)
        try:
            first=token.find("'")
            last=token.rfind("'")
            token=token[first+1:last]
            info=serializer.loads(token)  # 把token解密
            user_id=info['confirm']  # 取出解密后的用户ID
            user=Hmsx.objects.get(id=user_id)  # 查找出用户
            user.activate=1   # 修改激活状态
            user.save()
            return redirect('hmsx:info')
        except SignatureExpired as e:
            return HttpResponse("激活链接已过期")